// pages/circle/index.js
import { querySelectorAll } from "../../utils/query-selector"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{name: "广场"}, {name:"热门"}, {name: "关注", isDot: true}],
    currentIndex: 0,
    swiperItems: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    querySelectorAll(".swiper-item").then(res => {
      const swiperItems = res[0]
      this.setData({
        swiperHeight: swiperItems[0].height,
        swiperItems
      })
    })
    // 从本地存储中读取已关注的直播
    const followedLives = wx.getStorageSync('followedLives') || []
    this.setData({ followedLives })
    console.log('关注栏数据:', followedLives)
    // 动态计算 swiperHeight 以确保足够高度
    if (followedLives.length > 0) {
      const itemHeight = 300 // 每个直播项的高度（单位：rpx）
      const totalHeight = followedLives.length * itemHeight + 100 // 总高度加上额外空间
      this.setData({
        swiperHeight: totalHeight
      })
    }
  },

  changeTab: function(options) {
    this.setData({
      currentIndex: options.detail
    })
  },

  handleSwiperChange: function(event) {
    const current = event.detail.current
    this.setData({
      currentIndex: current,
      swiperHeight: this.data.swiperItems[current].height
    })
  },

  // 跳转到网页链接
  navigateToWeb: function(e) {
    // 获取data-url属性的值
    const url = e.currentTarget.dataset.url;
    
    // 检查是否有有效的链接
    if (url) {
      // 使用微信的web-view组件打开网页
      wx.navigateTo({
        url: `/pages/webview/index?url=${encodeURIComponent(url)}`
      });
    } else {
      wx.showToast({
        title: '链接不存在',
        icon: 'none'
      })
    }
  }
})